package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.DishDiAbleFailedBySetmealEnAbleException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 新增菜品和其对应的口味
     * @param dishDTO
     */
    @Transactional //开启事务，确保方法的原子性，保障菜品的新建后口味新建失败不会造成脏数据：注意：需要在启动类上开启事务
    public void saveWithFlavor(DishDTO dishDTO) {
        //因为菜品的新建可能会携带者口味，所以需要分来新建
        //1、向菜品表插入一条数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setStatus(0);
        dishMapper.insert(dish);
        Long dishId = dish.getId();

        //2、向口味表插入n条数据，因为一个菜可以有n个口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() >0){
            //因为在菜品中插入的数据后才能返回他的主键id，所以在口味表中关联的dishId始终为空，所以现在需要对其进行设置
            flavors.forEach(dishFlavor ->{
                dishFlavor.setDishId(dishId);
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //1、设置分页插件
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        //开始查询:
        /*为什么返回对象是个page对象？
        是因为在使用分页插件进行分页查询时，MyBatis会将查询结果封装到Page对象中，以便提供方便的分页信息和操作
        例如：getTotal()：获取总记录数。
             getPages()：获取总页数。
             getPageNum()：获取当前页码。
             getPageSize()：获取每页记录数。
             getResult()：获取当前页的查询结果数据。*/
        Page<DishVO>  page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 菜品批量删除
     * @param ids
     */
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //1、判断当前菜品是否能够删除--是否存在起售中？
        for (Long id : ids) {
            Dish dish = dishMapper.selectById(id);
            if (dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //2、判断当前菜品是否能够删除--是否被套餐关联？
        List<Long> setmealIds = setmealMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() > 0){
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }
        //3、删除菜品表中的菜品数据
        for (Long id : ids) {
            dishMapper.deleteById(id);
            //4、删除菜品关联的口味表数据
            dishFlavorMapper.deleteByDishId(id);
        }
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    public DishVO getByIdWithFlavor(Long id) {
        //1、根据菜品id查询菜品数据
        Dish dish = dishMapper.selectById(id);

        //2、根据菜品id查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);

        //3、将查询到的数据封装到VO当中
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }

    /**
     * 修改菜品（包含口味）
     * @param dishDTO
     */
    @Transactional
    public void update(DishDTO dishDTO) {
        //1、修改菜品相关内容
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish); //把前面的赋值给后面的
        dishMapper.update(dish);

        //2、修改口味相关内容
        //a、删除原有的口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        //b、重新插入新的口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() >0){
            flavors.forEach(dishFlavor ->{
                dishFlavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }

    }
    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> list(Integer categoryId) {
        List<Dish> list = dishMapper.listBycategoryId(categoryId);
        return list;
    }

    /**
     * 菜品的起售和停售
     * @param status
     * @param id
     */
    public void startOrStop(Integer status, Long id) {
        if (status == StatusConstant.ENABLE) {
            Dish dish = Dish.builder()
                    .status(status)
                    .id(id)
                    .build();
            dishMapper.update(dish);
        }else {
            List<SetmealDish> setmealDishes = setmealDishMapper.selectByDisId(id);
            setmealDishes.forEach(setmealDish -> {
                Long setmealId = setmealDish.getSetmealId();
                Setmeal setmeal = setmealMapper.selectById(setmealId);
                if (setmeal.getStatus() == StatusConstant.ENABLE){
                    throw new DishDiAbleFailedBySetmealEnAbleException(MessageConstant.DISH_DIABLE_FAILED_BY_SETMEAL_ENABLE);
                }else {
                    Dish dish = Dish.builder()
                            .status(status)
                            .id(id)
                            .build();
                    dishMapper.update(dish);
                }
            });
        }
    }
}
